package com.example.jianbing.juc;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @ClassName : ReadWirteLockDemo
 * @Description :
 * @Author : JB
 * @Date: 2020-08-07 00:44
 */

class MyCache{
    private volatile Map<String,Object> map = new HashMap<>();
    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    public void put(String key,Object value){
        readWriteLock.writeLock().lock();
        try{
            System.out.println(Thread.currentThread().getName()+"\t写入数据"+key);
            map.put(key,value);
            System.out.println(Thread.currentThread().getName()+"\t写入成功");
        }finally {
            readWriteLock.writeLock().unlock();
        }

    }

    public void get(String key){
        readWriteLock.readLock().lock();
        try{
            System.out.println(Thread.currentThread().getName()+"\t读取数据");
            Object result = map.get(key);
            System.out.println(Thread.currentThread().getName()+"\t读取成功"+result);
        }finally {
            readWriteLock.readLock().unlock();
        }

    }
}
public class ReadWirteLockDemo {
    public static void main(String[] args) {
            MyCache cache = new MyCache();
        for (  int i = 0; i < 5; i++) {
            final  int  temp = i;
            new Thread(()->{
                cache.put(temp+"",temp+"");
            },String.valueOf(i)).start();
        }
        for ( int i = 0; i < 5; i++) {
            final  int  temp = i;
            new Thread(()->{
                cache.get(temp+"");
            },String.valueOf(i)).start();
        }
    }
}
